<?php namespace App\Models;

use \System\Model;

class Story extends Model
{
    protected $table  = "story";
    protected $id     = 'id';
    protected $fields = ['id', 'title', 'author', 'desc', 'vote', 'score'];

    private $book;

    public function save($story)
    {
        $this->book = $story;
        if ($this->find($story['id'])) {
            $this->update($story);
        } else {
            $this->db->insert($this->table, $story);
            $this->createDB($story);
            $statModel = new \App\Models\Stat();
            $stat      = $statModel->where('date', date("Y-m-d"))->first();
            if ($stat) {
                $stat['story']++;
            } else {
                $stat = [
                    'date'     => date("Y-m-d"),
                    'visit'    => 1,
                    'story'    => 1,
                    'download' => 0,
                ];
            }
            $statModel->save($stat);
        }
    }

    public function createDB($story)
    {
        $sql = <<<EOT
CREATE TABLE  IF NOT EXISTS `{$story['id']}` (
  `id` int(11) NOT NULL auto_increment,
  `title` varchar(50) NOT NULL,
  `content` blob NOT NULL,
  `sort` int(6) NOT NULL,
  primary key(id)
) ENGINE=myisam DEFAULT CHARSET=utf8;
EOT;

        $this->db->query($sql);
        return $this;
    }

    public function download($story)
    {
        switch ($story['type']) {
            case "cloud":
                $this->cloudChapterList($story, true);
                break;
            case "html":
                break;
            case "text":
            default:
                break;
        }
    }

    public function downloadChapter($storyID, $chapter)
    {
        $api                = new \App\Models\Api(1);
        $body               = $api->getUrl("chapter", ["sp" => $chapter['link'], "k" => "2124b73d7e2e1945", "t" => "1468223717"], true, false);
        $chapter['title']   = $this->db->escape($chapter['title']);
        $chapter['content'] = $this->db->escape($body['chapter']['body']);
        $sql                = "INSERT INTO `{$storyID}` VALUE (0,'{$chapter['title']}',COMPRESS('{$chapter['content']}'),{$chapter['sort']})";
        $this->db->query($sql);
        if ($this->db->error) {
            showError($this->db->error);
        }

    }

    public function cloudChapterList($story, $download = false, $flush = false)
    {
        $api         = new \App\Models\Api(1);
        $chapterList = $api->getUrl("chapterList", ["sp" => $story['cloud'], "view" => "chapters"]);
        $last        = false;
        if ($download) {
            $i            = 0;
            $chapterTemp  = [];
            $chapterTable = $this->db->table($story['id'])->select("title")->get()->result();
            foreach ($chapterTable as $c) {
                $chapterTemp[] = $c['title'];
            }
            if ($flush) {
                set_time_limit(0);
                if (ob_get_contents()) {
                    ob_end_clean();
                }

                ob_implicit_flush();
                echo "<p>" . $story['title'] . "</p>";
            }
            foreach ($chapterList['chapters'] as $chapter) {
                $i++;
                if (in_array($chapter['title'], $chapterTemp)) {
                    continue;
                }

                $c = ["title" => $chapter['title'], "link" => \urlencode($chapter['link'])];
                if ($flush) {
                    echo $chapter['title'];
                    //echo str_repeat(" ", 1024);
                }
                $c['sort'] = $i;
                $this->downloadChapter($story['id'], $c);
                $last = true;
            }
            //如果有更新
            if ($last) {
                //获取最后一个章节ID
                $lastChapter = $this->db->table($story['id'])->select("id")->order("id", "DESC")->get()->first();
                $update      = [
                    'last_update'     => time(),
                    "last_chapter"    => $chapter['title'],
                    "last_chapter_id" => $lastChapter['id'],
                ];
                $this->db->update("story", $update, ['id' => $story['id']]);
            }
        }
        return $chapterList['chapters'];
    }

    public function chapters($id, $order)
    {
        return $this->db->table($id)->select("id,title")->order("sort", $order)->get()->result();
    }

    public function chapter($storyID, $chapterID)
    {
        return $this->db->table($storyID)->select("id,title,UNCOMPRESS(content) as content")->where("id", $chapterID)->get()->first();
    }

    public function deleteStory($storyID)
    {
        $sql = "DROP TABLE {$storyID}";
        $this->db->query($sql);
        if ($this->db->error) {
            showError($this->db->error);
        }

        $this->delete($storyID);
    }
}
